import { defineComponent, ref, onMounted, watch, computed } from 'vue';

import crossWindowMessenger from './lib/crossWindowMessenger.js';
import { ACK_MAPPING } from './lib/useMessage.js';

export default defineComponent({
  props: {
    config: {
      type: Object,
      default() {
        return {
          baseUrl: '',
          token: '',
        };
      },
    },
    copilotProps: {
      type: Object,
    },
    variables: {
      type: Object,
      default() {
        return {};
      },
    },
    visible: {
      type: Boolean,
      default() {
        return false;
      },
    },
    iframeVisible: {
      type: Boolean,
      default() {
        return false;
      },
    },
  },
  emits: ['taiTool'],
  setup(props, { attrs, emit, expose, slots }) {
    const configKey = 'TCopilotChatbotConfig';
    const buttonId = 'fasr-chatbot-bubble-button';

    const toolsMapping = computed(() => {
      return props.copilotProps?.tools?.reduce((r, tool) => {
        r[`TOOL_${tool.id}`] = tool;
        return r;
      }, {});
    });

    const receiveMessage = event => {
      switch (event.data.type) {
        case 'TAI_READY':
          crossWindowMessenger.init(event.source.window, event.origin);
          // this[`ACK_${event.data.type}`](event);
          publicMethod.refresh();
          break;
        case 'TAI_TOOL':
          const callback = event.data.payload.callback;
          const taiToolPayload = toolsMapping.value[callback];
          if (taiToolPayload) {
            emit('taiTool', taiToolPayload);
          }

          break;
      }
    };

    watch(
      () => props.variables,
      val => {
        publicMethod.updateVariables(val);
      },
      { deep: true },
    );

    watch(
      () => props.iframeVisible,
      val => {
        if (val) {
          showIfrmae.value = true;
          isIframeMounted.value = true;
        }
      },
    );

    watch(
      () => props.visible,
      val => {
        // if (false == val) {
        //   showIfrmae.value = false;
        //   // publicMethod.refresh();
        // } else {
        //   showIfrmae;
        // }
        if (isIframeMounted.value) showIfrmae.value = val;
      },
    );

    const isIframeMounted = ref(false);
    const showIfrmae = ref(false);

    const readerChatBotIframe = ({ style = {} } = {}) => {
      return (
        <iframe
          // v-show={props.modelValue}
          id={props.iframeId}
          src={`${props.config.baseUrl}${props.config.token}`}
          style={{
            position: 'absolute',
            bottom: '0',
            right: '0',
            width: '24rem',
            height: '43.75rem',
            border: 'none',
            zIndex: 2147483640,
            marginBottom: '60px',
            ...attrs.style,
          }}
        ></iframe>
      );
    };

    onMounted(() => {
      crossWindowMessenger?.receiveMessage(receiveMessage);
    });

    const publicMethod = {
      updateVariables: variables => {
        ACK_MAPPING.SYNC_VARIABLES(variables, {
          _description_: props.copilotProps.description,
        });
      },
      refresh: () => {
        ACK_MAPPING.ACK_TAI_READY({
          ...props.copilotProps,
          variables: props.variables,
        });
      },
    };
    expose({ ...publicMethod });
    return () => <>{showIfrmae.value && readerChatBotIframe()}</>;
  },
});
